package com.lsc.context;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.lsc.strategy.BashStrategy;
import com.lsc.util.ObjectUtils;
import com.lsc.util.StringUtils;

/**
 * 商店优惠方式工厂类
 * @author LSC
 */
public class StrategyContext {
	private BashStrategy stretegy;
	public static String xmlPath = "E:/Strategy.xml";

	public StrategyContext(String condition) {
		if(StringUtils.isEmpty(condition)){
			return ;
		}
		initStrategy(condition);
	}
	
	
	/**
	 * 初始化销售方案,实例化优惠方式
	 * @param condition
	 */
	private void initStrategy(String condition){
		List<Map<String,Object>> strategyList = getXMLList(xmlPath);
		for(Map<String,Object> m : strategyList){
			if(m.get("name").equals(condition)){
				stretegy = (BashStrategy) ObjectUtils.newObject(m.get("value").toString(),m.get("param"));		
			}
		}
	}
	
	/**
	 * 输出结算金额
	 * @param money
	 */
	public void getResult(double money){
		if(StringUtils.isEmpty(stretegy)){
			System.err.println("未找到该销售方案，对象未被实例化");
			return ;
		}
		stretegy.printReslt(money);
	}
	
	/**
	 * 解析xml
	 * @param path   文件路径
	 * @return List<Map<String,Object>>
	 */
	private List<Map<String,Object>> getXMLList(String path){
		List<Map<String,Object>> strategyList = new ArrayList<Map<String,Object>>();
		try {   
		     File file = new File(path);   
		    SAXReader reader = new SAXReader();   
		     Document doc =  reader.read(file);   
		     Element root = doc.getRootElement();
		  
		    for (Iterator i = root.elementIterator("strategy"); i.hasNext();) {   
		    	 List<List> paramList =new ArrayList<List>();
	         	Map<String,Object> map = new HashMap<String,Object>();
		        Element strategy = (Element) i.next();
		        map.put("name", strategy.elementText("name"));
		        map.put("value", strategy.elementText("value"));
		        for (Iterator j = strategy.elements("params").iterator(); j.hasNext();) { 
		        	 Element params = (Element) j.next();
		        	 List<Map<String,Object>> paramsMap =new ArrayList<Map<String,Object>>();
		        	  for (Iterator m = params.elements("param").iterator(); m.hasNext();) { 
		        		  Map<String,Object> paramMap = new HashMap<String,Object>();
		        		  Element param = (Element) m.next();
		        		  paramMap.put("value", param.getText());
			        	  paramsMap.add(paramMap);
		        	  }
		        	  paramList.add(paramsMap);
		        }
		        map.put("param", paramList);
			    strategyList.add(map);
		    }

		  } catch (Exception e) {   
			   		e.printStackTrace();   
		  } 
		return strategyList;
	}

}
